/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package threads;

import filters.ByteStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import own_packets.Protocol;

/**
 *
 * @author Hnmtuan
 */
public class TestConnection implements Runnable {

    private String _host;
    private Integer _port;
    private Socket _ownSocket;
    private InputStream _in;
    private OutputStream _output;
    private ObjectOutputStream _objOutput;

    public TestConnection(String host, Integer port) {
        _host = host;
        _port = port;
    }

    public void run() {
        try {
            // Connection to server with hostname, portname
            _ownSocket = new Socket(_host, _port);

            // Create outputStream to send data to a following server
            _output = _ownSocket.getOutputStream();

            // Send request type as test connection to a following server
            if (_output == null) {
                System.out.println("Connect to a following server is failed");
                return;
            }

            // Create packet to send a following server
            Protocol myPacket = new Protocol();
            myPacket.setIsRequest(Boolean.TRUE);
            myPacket.setMessages("Request Search File");

            // Forward packet to a following server
            ByteStream.toStream(_output, myPacket);

            // Create inputStream to received data from a following server
            _in = _ownSocket.getInputStream();

            // Received Response from a following server
            Protocol objRS = ByteStream.toProtocol(_in);
            
            if (objRS == null) {
                System.out.println("Received Null Object From Server");
                return;
            }
            // Output result to layout
            System.out.println(String.format("Messages from server : %s", objRS.getMessages()));

        } catch (ClassNotFoundException ex) {
            System.out.println(String.format("Failed TestConnection Thread : %s", ex.getMessage()));
        } catch (UnknownHostException ex) {
            System.out.println(String.format("Failed TestConnection Thread : %s", ex.getMessage()));
        } catch (IOException ex) {
            System.out.println(String.format("Failed TestConnection Thread : %s", ex.getMessage()));
        } finally {
            try {
                _ownSocket.close();
            } catch (IOException ex) {
                System.out.println(String.format("Failed TestConnection Thread : %s", ex.getMessage()));
            }
        }
    }
}
